import { defineStore } from 'pinia'
import { GET_Refresh_TOKEN, GET_TOKEN, SET_Refresh_TOKEN, SET_TOKEN } from '@/utils/token'
import { reqLogin } from '@/api/user'

const useUserStore = defineStore('User', {
    state: () => ({
        token: GET_TOKEN(),
        refresh_token: GET_Refresh_TOKEN(),
        username: ''
    }),

    actions: {
        // 用户登录方法
        async userLogin(data: any) {
            try {
                const result: any = await reqLogin(data)
                if (result.code === 200) {
                    this.token = result.data.access
                    this.refresh_token = result.data.refresh
                    SET_TOKEN(result.data.access)
                    SET_Refresh_TOKEN(result.data.refresh)
                    return 'ok'
                } else {
                    return Promise.reject(new Error(result.data))
                }
            } catch (error) {
                return Promise.reject(new Error('登录失败，请重试'))
            }
        },
    },

    getters: {},
})

export default useUserStore
